import os
import sys
import pyttsx3
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


class Speak(QWidget):

    def __init__(self):
        super(Speak, self).__init__()

        self.setWindowTitle('小喇叭')
        self.main_layout=QHBoxLayout()
        self.text_edit=QTextEdit()
        self.speak_btn=QPushButton('播放')
        self.speak_btn.clicked.connect(self._say)
        self.speak_btn.setMinimumHeight(50)
        self.save_btn=QPushButton('保存音频')
        self.save_btn.clicked.connect(self._save)
        self.main_layout.addWidget(self.text_edit)
        self.main_layout.addWidget(self.speak_btn)
        self.main_layout.addWidget(self.save_btn)
        self.setLayout(self.main_layout)

        self.engine=pyttsx3.init()
        self.engine.setProperty('voice', 'zh')
        rate =  self.engine.getProperty('rate')
        self.engine.setProperty('rate',  rate - 30)
        volume = self.engine.getProperty('volume')
        self.engine.setProperty('volume', volume + 11)


    def _say(self):
        text=self.text_edit.toPlainText()
        if text:
            self.engine.say(text)
            self.engine.runAndWait()

    def _save(self):
        text=self.text_edit.toPlainText()
        if text:
            self.engine.save_to_file(text , 'test.wav')
            self.engine.runAndWait()


if __name__ == '__main__':
    app=QApplication(sys.argv)
    s=Speak()
    s.show()
    sys.exit(app.exec_())